from datetime import datetime

from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request

from info import constants
from info import db
from info.models import Category, News, User
from info.response_code import RET
from info.utils import image_storage
from info.utils.commen import user_login_data
from . import profile_blu


@profile_blu.route('/other_news')
def other_news():
    """其他用户发布的新闻列表分页展示"""
    page = request.args.get('page', 1)
    user_id = request.args.get('user_id')
    if not all([page, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    curr_page = 1
    total_page = 1
    news_list = []
    try:
        paginate = user.news_list.paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        curr_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_dict())

    data = {
        "current_page": curr_page,
        "total_page": total_page,
        "news_list": news_dict_li
    }
    return jsonify(errno=RET.OK, errmsg='ok', data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """其他用户的信息展示
    1.接收其他用户的id 判断参数
    2.查询用户信息并返回给前端
    3.前端需要显示自己的登录状态 并返回其他用户的信息
    """
    user = g.user
    user_id = request.args.get('user_id')
    if not user_id:
        abort(404)

    other = None

    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 是否关注当前用户
    # 默认关注状态为false
    is_followed = False
    if user:
        if other in user.followed:
            is_followed = True

    data = {
        "other_info": other.to_dict(),
        "user_info": user.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """个人中心关注用户列表
    1.请求页面时返回关注用户的个人信息
    2.获取分页参数  查询数据并返回
    """
    user = g.user
    page = request.args.get('page', 1)
    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    curr_page = 1
    total_page = 1
    user_list = []
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        curr_page = paginate.page
        total_page = paginate.pages
        user_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []
    for users in user_list:
        user_dict_li.append(users.to_dict())

    data = {
        "current_page": curr_page,
        "total_page": total_page,
        "users": user_dict_li
    }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    """显示用户发布的新闻列表
    1.因为不需要进行修改操作，所以用get方法
    2.获取页数
    3.判断
    4.分页查询数据
    5.返回数据给前端
    """
    page = request.args.get('p')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    current_page = 1
    total_page = 1
    news_list = []
    try:
        paginate = user.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_list": news_dict_list
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods=['post', 'get'])
@user_login_data
def news_release():
    """新闻发布
    1.如果是get,返回新闻发布页面的时候返回新闻分类给前端  移除最新的分类
    2.post说明是发布新闻，接收参数  标题 摘要 分类 内容 图片
    3.验证参数
    4.
    """
    if request.method == 'GET':
        categories = []
        # 获取新闻分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        cate_list = []
        for category in categories:
            cate_list.append(category.to_dict())
        # 移除最新分类
        cate_list.pop(0)
        data = {
            "categories": cate_list
        }
        return render_template('news/user_news_release.html', data=data)

    # 代码执行到此说明是发布新闻的请求
    # 获取参数，以ajaxSubmit方式发送的类似表单请求，可以取出带有name属性的input的值
    source = '个人发布'
    title = request.form.get('title')
    digest = request.form.get('digest')
    category_id = request.form.get('category_id')
    content = request.form.get('content')
    index_image = request.files.get('index_image')

    if not all([source, title, digest, category_id, content, index_image]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 取出图片，上传到七牛云，保存图片的key
    try:
        key = image_storage.storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='图片保存失败')

    # 创建新闻模型
    user = g.user
    news = News()
    news.category_id = category_id
    news.content = content
    news.digest = digest
    news.create_time = datetime.now()
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.title = title
    news.source = source
    news.user_id = user.id
    # status=1表示审核中  0 表示通过  -1 表示为通过
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route('/collections')
@user_login_data
def collections():
    """显示用户收藏的新闻
    1.因为不需要进行修改操作，所以用get方法
    2.获取页数
    3.判断
    4.分页查询数据
    5.返回数据给前端
    """
    page = request.args.get('p')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    current_page = 1
    total_page = 1
    news_list = []
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_list": news_dict_list
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/user_password', methods=['post', 'get'])
@user_login_data
def user_password():
    """修改密码
    1.接收用户传入的新旧密码
    2.校验原密码
    3.设置新密码
    4.返回结果
    """
    user = g.user
    # 密码修改界面不需要显示原密码
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    old_pwd = request.json.get('old_password')
    new_pwd = request.json.get('new_password')
    if not all([old_pwd, new_pwd]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if not user.check_passowrd(old_pwd):
        return jsonify(errno=RET.PWDERR, errmsg='原密码错误')

    # 设置新密码
    user.password = new_pwd
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='保存密码失败')

    # 返回结果给前端
    return jsonify(errno=RET.OK, errmsg='ok')


@profile_blu.route('/pic_info', methods=['post', 'get'])
@user_login_data
def pic_info():
    """修改头像
    1.接收用户传入的图片文件
    2.校验文件
    3.上传图片到七牛云  返回值为key
    4.保存key到user表里的avatar_url
    5.将拼接好的头像外链地址返回给前端
    """
    user = g.user
    if request.method == 'GET':
        data = {
            "user_info": user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)

    # 代码执行到此说明是post请求修改头像
    pic = request.files.get('avatar').read()
    if not pic:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 上传图片到七牛云
    try:
        key = image_storage.storage(pic)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='保存图片失败')

    # 将key作为用户头像的参数保存到数据库
    user.avatar_url = key
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='保存图片失败')

    return jsonify(errno=RET.OK, errmsg='ok', data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=['post', 'get'])
@user_login_data
def base_info():
    """显示基本资料
    1.判断用户是否登录
    2.判断用户发送的请求是get还是post
    3.如果是get,返回基本资料模板
    4.如果是post,接收参数  用户名   个性签名  性别
    5.校验参数
    6.保存数据到数据库
    7.返回结果
    """
    user = g.user
    if not user:
        return redirect('/')
    if request.method == 'GET':
        return render_template('news/user_base_info.html', data={"user": user.to_dict() if user else None})
    # 代表是修改用户数据
    # 1. 取到传入的参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2. 校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ("WOMAN", "MAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/info')
@user_login_data
def user_():
    if not g.user:
        return redirect('/')
    data = {
        "user_info": g.user.to_dict(),
    }
    return render_template('news/user.html', data=data)
